import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:family_app/src/common/constants.dart';
import 'package:family_app/src/common/router.dart';
import 'package:family_app/src/features/auth/screens/login_screen.dart';
import 'package:family_app/src/features/home/screens/home_screen.dart';
import 'package:family_app/src/theme/app_theme.dart';

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化日期格式化
  await initializeDateFormatting('zh_CN', null);

  // 关闭所有调试绘制模式和调试标记
  debugPaintSizeEnabled = false;
  debugPaintBaselinesEnabled = false;
  debugPaintLayerBordersEnabled = false;
  debugPaintPointersEnabled = false;
  debugRepaintRainbowEnabled = false;
  debugPrintMarkNeedsLayoutStacks = false;
  debugPrintMarkNeedsPaintStacks = false;
  debugPrintLayouts = false;
  debugProfileLayoutsEnabled = false;
  debugProfilePaintsEnabled = false;
  debugDisableShadows = false;

  // 设置屏幕方向
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  // 初始化Hive本地存储
  await Hive.initFlutter();
  await Hive.openBox(AppConstants.userBox);
  await Hive.openBox(AppConstants.galleryBox);
  await Hive.openBox(AppConstants.financeBox);
  await Hive.openBox(AppConstants.secureVaultBox);

  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 获取用户登录状态
    final userBox = Hive.box(AppConstants.userBox);
    final isLoggedIn = userBox.get('isLoggedIn', defaultValue: false);
    
    return ScreenUtilInit(
      // 设计稿尺寸 (iPhone 13 Pro)
      designSize: const Size(390, 844),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return MaterialApp(
          title: AppConstants.appName,
          debugShowCheckedModeBanner: false,
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.darkTheme,
          themeMode: ThemeMode.system,
          routes: AppRouter.routes,
          onGenerateRoute: AppRouter.onGenerateRoute,
          onUnknownRoute: AppRouter.onUnknownRoute,
          home: isLoggedIn ? const HomeScreen() : const LoginScreen(),
        );
      },
    );
  }
}
